<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="班级名称" prop="className">
        <el-input
            v-model="queryParams.className"
            placeholder="请输入班级名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学生姓名" prop="studentName">
        <el-input
            v-model="queryParams.studentName"
            placeholder="请输入学生姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="考试科目" prop="examName">
        <el-input
            v-model="queryParams.examName"
            placeholder="请输入考试科目"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评分状态" prop="scoreStatus">
        <el-select
            v-model="queryParams.scoreStatus"
            placeholder="请选择评分状态"
            clearable
        >
          <el-option
              v-for="item in scoreStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table
        v-loading="loading"
        :data="scoreList"
        @selection-change="handleSelectionChange"
        :key="tableKey"
    >
      <el-table-column label="班级名称" align="center" prop="className"/>
      <el-table-column label="学生姓名" align="center" prop="studentName"/>
      <el-table-column label="考试科目" align="center" prop="examName"/>
      <el-table-column label="最低成绩" align="center">
        <template #default="scope">
          <span>{{ scope.row.worstScore || '-' }}分</span>
        </template>
      </el-table-column>
      <el-table-column label="提交时间" align="center" width="180">
        <template #default="scope">
          <span>{{ scope.row.submitTime ? parseTime(scope.row.submitTime, '{y}-{m}-{d} {h}:{i}') : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="评分状态" align="center">
        <template #default="scope">
          {{ formatScoreStatus(scope.row.scoreStatus) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleReview(scope.row)"
                     >复核
          </el-button>
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)"
                     >查看试卷
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 成绩复核对话框 -->
    <el-dialog :title="reviewTitle" v-model="reviewOpen" width="500px" append-to-body>
      <el-form ref="reviewRef" :model="reviewForm" :rules="reviewRules" label-width="80px">
        <el-form-item label="最终评分" prop="finalScore">
          <el-input-number v-model="reviewForm.finalScore" :precision="2" :step="0.5" :min="0" :max="100"/>
        </el-form-item>
        <el-form-item label="复核意见" prop="comments">
          <el-input v-model="reviewForm.comments" type="textarea" placeholder="请输入复核意见"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitReview">确 定</el-button>
          <el-button @click="cancelReview">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
        :title="`${detailData.studentName} - ${detailData.examName}`"
        v-model="detailOpen"
        width="70%"
        append-to-body
    >
      <div v-if="fileLoading" style="text-align: center; padding: 20px;">
        <el-icon class="is-loading" size="large"><Loading /></el-icon>
        <span style="margin-left: 10px;">正在加载试卷内容...</span>
      </div>
      <div v-else>
        <!-- 直接显示原始数据 -->
        <div v-if="detailData.fileContent" class="data-container">
          <pre v-if="isStringContent">{{ detailData.fileContent }}</pre>
          <vue-json-pretty
              v-else
              :data="detailData.fileContent"
              :deep="2"
              showLength
          />
        </div>
        <div v-else class="empty-content">
          <el-empty description="暂无试卷内容"></el-empty>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="detailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="StudentScores">
import {listWorstScores, reviewScore} from "@/api/Teacher/students.js"
import {parseTime} from '@/utils/ruoyi'
import {nextTick} from 'vue'
import {useExampleStore} from "@/stores/exampleStore.js";
import VueJsonPretty from 'vue-json-pretty'
import 'vue-json-pretty/lib/styles.css'
import {Loading} from "@element-plus/icons-vue";

// 在setup中注册组件
components: {
  VueJsonPretty,
      Loading
}

const {proxy} = getCurrentInstance()

const tableKey = ref(0)
const scoreList = ref([])
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const reviewOpen = ref(false)
const reviewTitle = ref("")
const detailOpen = ref(false)
const detailData = ref({})
const queryRef = ref()
const reviewRef = ref()
// 在其他 ref 定义附近添加
const fileLoading = ref(false); // 初始值为 false（未加载）

// 评分状态选项
const scoreStatusOptions = ref([
  {value: 'auto_graded', label: '自动评分'},
  {value: 'pending_review', label: '待复核'},
  {value: 'reviewed', label: '已复核'},
  {value: 'rejected', label: '已驳回'}
])

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    className: null,
    studentName: null,
    examName: null,
    scoreStatus: null
  },
  reviewForm: {
    recordId: null,
    studentId: null,
    examId: null,
    finalScore: null,
    comments: null
  },
  reviewRules: {
    finalScore: [
      {required: true, message: "最终评分不能为空", trigger: "blur"},
      {
        validator: (rule, value, callback) => {
          if (value < 0 || value > 100) {
            callback(new Error('分数必须在0-100之间'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ],
    comments: [
      {required: true, message: "复核意见不能为空", trigger: "blur"},
      {max: 500, message: "复核意见长度不能超过500个字符", trigger: "blur"}
    ]
  }
})

const {queryParams, reviewForm, reviewRules} = toRefs(data)
const exampleStore = useExampleStore();
const school = exampleStore.getSchool;


const isStringContent = computed(() => {
  return typeof detailData.value.fileContent === 'string'
})
async function getList() {
  try {
    loading.value = true;
    queryParams.value.schoolId = school // 假设school对象有id属性
    console.log("查询参数", queryParams.value)
    //console.log('请求参数:', {...queryParams.value});

    const response = await listWorstScores(queryParams.value);
    console.log('完整响应:', response);

    if (scoreList.value.length > 0) {
      console.log('第一条记录字段:', Object.keys(scoreList.value[0]));
      console.log('第一条记录内容:', scoreList.value[0]);
    }

    if (response?.code === 0) {  // 注意这里改为检查code === 0
      scoreList.value = response.data?.list || [];  // 注意访问data.list
      total.value = response.data?.total || 0;

      // 强制更新
      await nextTick();
      tableKey.value++;
    } else {
      console.error('API返回异常:', response?.message);
    }
  } catch (error) {
    console.error('请求失败:', error);
  } finally {
    loading.value = false;
  }
}

// 格式化评分状态
function formatScoreStatus(status) {
  const map = {
    'auto_graded': '自动评分',
    'pending_review': '待复核',
    'reviewed': '已复核',
    'rejected': '已驳回'
  }
  return map[status] || status
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.recordId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 复核按钮操作 */
async function submitReview() {
  try {
    await proxy.$refs.reviewRef.validate();

    const submitData = {
      studentId: Number(reviewForm.value.studentId),
      examId: Number(reviewForm.value.examId),
      finalScore: Number(reviewForm.value.finalScore),
      recordId: reviewForm.value.recordId,
      comments: reviewForm.value.comments.toString(),
    };
    console.log('提交数据:', submitData);

    const response = await reviewScore(submitData);
    console.log('API 返回:', response);

    const isSuccess = response?.code === 200 ||
        response?.code === 0 ||
        response?.success === true;

    if (isSuccess) {
      proxy.$modal.msgSuccess(response.message || "复核成功");
      reviewOpen.value = false;
      await getList();
    } else {
      throw new Error(response?.message || "复核失败");
    }
  } catch (error) {
    console.error('复核失败:', error);
    proxy.$modal.msgError(`复核失败: ${error.message || '未知错误'}`);
  }
}

function handleReview(row) {
  console.log('复核行完整数据:', {
    idFields: {
      studentId: row.studentId,
      examId: row.examId,
      recordId: row.recordId
    },
    allData: row
  });

  reviewForm.value = {
    recordId: row.recordId || row.id,
    studentId: row.studentId,
    examId: row.examId,
    finalScore: row.worstScore || 0,
    comments: ''
  };

  reviewOpen.value = true;
  reviewTitle.value = `成绩复核 - ${row.studentName}`;
}

// 取消复核
function cancelReview() {
  reviewOpen.value = false
  resetReview()
}

// 重置复核表单
function resetReview() {
  reviewForm.value = {
    recordId: null,
    studentId: null,
    examId: null,
    finalScore: null,
    comments: null
  }
  proxy.resetForm("reviewRef")
}

/** 详情按钮操作 */
function handleDetail(row) {
  detailOpen.value = true
  fileLoading.value = true

  // 重置detailData
  detailData.value = {
    studentName: row.studentName,
    examName: row.examName,
    fileContent: null
  }

  console.log('原始数据:', row)

  // 延迟设置以观察响应式变化
  setTimeout(() => {
    if (row.fileContent) {
      try {
        // 尝试解析JSON
        const parsed = typeof row.fileContent === 'string'
            ? JSON.parse(row.fileContent)
            : row.fileContent
        detailData.value.fileContent = parsed
        // 关键：用 JSON.stringify 格式化打印，第三个参数控制缩进
        console.log('解析后的内容（完整展开）:', JSON.stringify(parsed, null, 2));
      } catch (e) {
        console.log('使用原始内容:', row.fileContent)
        detailData.value.fileContent = row.fileContent
      }
    }
    fileLoading.value = false
  }, 500)
}
onMounted(() => {
  getList().then(() => {
    console.log('初始化数据加载完成', scoreList.value)
  })
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.el-table {
  min-height: 300px;
}

.json-viewer {
  background: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  max-height: 60vh;
  overflow: auto;
}

.json-viewer pre {
  margin: 0;
  font-family: Consolas, Monaco, 'Andale Mono', monospace;
  line-height: 1.5;
  color: #333;
}
</style>